package com.voute.View.Fragement;

import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.voute.Base.BaseFragment;
import com.voute.Model.Action.UpCommentAction;
import com.voute.Model.Bean.BaseBean;
import com.voute.Model.Bean.CommentsBean;
import com.voute.Model.Bean.FeedCommentEntity;
import com.voute.Model.Bean.UxTagBean;
import com.voute.Model.Impl.FeedDetailModelImpl;
import com.voute.Model.Impl.UXTagModelImpl;
import com.voute.Presenter.IGetCommentsPresenter;
import com.voute.Presenter.Impl.GetCommentsPresenterImpl;
import com.voute.R;
import com.voute.Utils.CommonSubscriber;
import com.voute.Utils.RxBus;
import com.voute.Utils.TransformUtils;
import com.voute.View.Adapter.FeedDetailCommentAdapter;
import com.voute.View.IView.IGetCommentsView;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * 评论Fragment,最热门以及最新的评论复用这一个画面
 * Created by liucxu on 2017/3/7.
 */

public class CommentsFragment extends BaseFragment implements IGetCommentsView {

    /**
     * 选择框的UI控件
     */
    private ImageView imv_left_positive;

    private RelativeLayout layout_positive_layout;
    private ImageView imv_feed_detail_to_right;
    private ImageView left_line_imv;

    private RelativeLayout layout_both_layout;
    private ImageView both_line_imv;
    private ImageView imv_feed_detail_to_both;

    private RelativeLayout layout_right_layout;
    private ImageView right_line_imv;
    private ImageView imv_feed_detail_to_left;

    private ImageView imv_right_positive;

    private TextView tv_instant_comment;
    private SwipeRefreshLayout swipe_refresh_layout;
    private ListView content_list_view;

    private FeedDetailCommentAdapter adapter;
    private ArrayList<FeedCommentEntity> datas;
    private ArrayList<FeedCommentEntity> datas_to_show;
    private IGetCommentsPresenter presenter;

    private MaterialDialog progressDialog;

    private String comments_type = "";
    private String fid = "";
    private boolean is_newest_comment = true;
    private String anchor = "0";
    private int page = 1;
    private int position = 1;
    private boolean stopLoadMore;
    private boolean isLoading;
    private boolean isRefresh = true;

    private Subscription rxSubscription;


    @Override
    public int getLayoutId() {
        return R.layout.fragment_comments;
    }

    @Override
    public void setupView() {
        imv_left_positive = $(R.id.imv_left_positive);
        layout_positive_layout = $(R.id.layout_positive_layout);
        layout_positive_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isRefresh = true;
                refreshDataUIBySelected(0);
                position = 0;
                getPageFeedsComments(isRefresh);
            }
        });
        imv_feed_detail_to_right = $(R.id.imv_feed_detail_to_right);
        left_line_imv = $(R.id.left_line_imv);

        layout_both_layout = $(R.id.layout_both_layout);
        layout_both_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isRefresh = true;
                refreshDataUIBySelected(1);
                position = 1;
                getPageFeedsComments(isRefresh);
            }
        });
        both_line_imv = $(R.id.both_line_imv);
        imv_feed_detail_to_both = $(R.id.imv_feed_detail_to_both);

        layout_right_layout = $(R.id.layout_right_layout);
        layout_right_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isRefresh = true;
                refreshDataUIBySelected(2);
                position = 2;
                getPageFeedsComments(isRefresh);
            }
        });
        right_line_imv = $(R.id.right_line_imv);
        imv_feed_detail_to_left = $(R.id.imv_feed_detail_to_left);
        imv_right_positive = $(R.id.imv_right_positive);
        tv_instant_comment = $(R.id.tv_instant_comment);
        swipe_refresh_layout = $(R.id.swipe_refresh_layout);
        content_list_view = $(R.id.content_list_view);
        swipe_refresh_layout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                getPageFeedsComments(isRefresh);
            }
        });
        datas = new ArrayList<>();
        datas_to_show = new ArrayList<>();
        adapter = new FeedDetailCommentAdapter(getActivity(), datas);
        content_list_view.setAdapter(adapter);
        comments_type = getArguments().getString("comment_type");
        fid = getArguments().getString("fid");
        if ("new_comment".equals(comments_type)) {
            is_newest_comment = true;
        } else {
            is_newest_comment = false;
        }
        presenter = new GetCommentsPresenterImpl(this);
        presenter.getComments(is_newest_comment, fid, anchor, page + "");
        content_list_view.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {

            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                int last_visiable = absListView.getLastVisiblePosition();
                if (!stopLoadMore && !isLoading && (last_visiable > 0)) {
                    if (last_visiable + 2 > totalItemCount) {
                        isRefresh = false;
                        getPageFeedsComments(isRefresh);
                    }
                }
            }
        });
        rxSubscription = RxBus.getDefault().toObservable(UpCommentAction.class).subscribe(new Action1<UpCommentAction>() {
            @Override
            public void call(final UpCommentAction upCommentAction) {
                (new UXTagModelImpl()).getUxTag().flatMap(new Func1<UxTagBean, Observable<BaseBean>>() {
                    @Override
                    public Observable<BaseBean> call(UxTagBean uxTagBean) {
                        return (new FeedDetailModelImpl()).upComment(upCommentAction.getCid() + "", uxTagBean.getData().getUxtag(), upCommentAction.getSide());
                    }
                }).compose(TransformUtils.<BaseBean>defaultSchedulers()).subscribe(new CommonSubscriber<BaseBean>() {
                    @Override
                    public void onSuccess(BaseBean response) {
                        isRefresh = true;
                        getPageFeedsComments(isRefresh);
                    }

                    @Override
                    public void onFailure(BaseBean response) {
                        Snackbar.make(content_list_view, response.getMsg(), Snackbar.LENGTH_SHORT).show();
                    }
                });
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {

            }
        });
    }

    @Override
    public void setupData() {

    }

    private void refreshDataUIBySelected(final int position) {
        isRefresh = true;
        if (position == 0) {
            setSelectedPositive(true, false);
            setSelectedBoth(false);
            setSelectedNegative(false, true);
        } else if (position == 1) {
            setSelectedPositive(true, true);
            setSelectedBoth(true);
            setSelectedNegative(true, true);
        } else if (position == 2) {
            setSelectedPositive(false, true);
            setSelectedBoth(false);
            setSelectedNegative(true, false);
        }
    }

    private void setSelectedPositive(boolean selected, boolean hide_scroll) {
        if (selected) {
            if (hide_scroll) {
                imv_feed_detail_to_right.setVisibility(View.GONE);
            } else {
                imv_feed_detail_to_right.setVisibility(View.VISIBLE);
            }
            left_line_imv.setBackgroundResource(R.drawable.feed_detail_left_line);
            imv_feed_detail_to_right.setImageResource(R.mipmap.feed_detail_to_right);
            imv_left_positive.setImageResource(R.mipmap.feed_detail_left_positive_yellow);
        } else {
            imv_feed_detail_to_right.setVisibility(View.GONE);
            left_line_imv.setBackgroundResource(R.drawable.feed_detail_left_line_unselected);
            imv_left_positive.setImageResource(R.mipmap.feed_detail_left_positive_grey);
        }
    }

    private void setSelectedBoth(boolean selected) {
        if (selected) {
            imv_feed_detail_to_both.setVisibility(View.VISIBLE);
        } else {
            imv_feed_detail_to_both.setVisibility(View.GONE);
        }
    }

    private void setSelectedNegative(boolean selected, boolean hide_scroll) {
        if (selected) {
            if (hide_scroll) {
                imv_feed_detail_to_left.setVisibility(View.GONE);
            } else {
                imv_feed_detail_to_left.setVisibility(View.VISIBLE);
            }
            right_line_imv.setBackgroundResource(R.drawable.feed_detail_right_line);
            imv_right_positive.setImageResource(R.mipmap.feed_detail_right_negative_green);
            imv_feed_detail_to_left.setImageResource(R.mipmap.feed_detail_to_left);
        } else {
            imv_feed_detail_to_left.setVisibility(View.GONE);
            right_line_imv.setBackgroundResource(R.drawable.feed_detail_right_line_unselected);
            imv_right_positive.setImageResource(R.mipmap.feed_detail_right_negative_grey);
        }
    }

    @Override
    public void requestCommentsSuccess(CommentsBean beans) {
        swipe_refresh_layout.setRefreshing(false);
        if (beans != null) {
            if (beans.getStatus() == 0) {
                isLoading = false;
                if (isRefresh) {
                    anchor = "0";
                    page = 1;
                    datas.clear();
                    datas_to_show.clear();
                    isRefresh = false;
                }
                if (beans.getData() != null) {
                    if (beans.getData().getComments() != null && beans.getData().getComments().size() > 0) {
                        page = page + 1;
                        datas.addAll(beans.getData().getComments());
                        datas_to_show.addAll(filterComments(beans.getData().getComments()));
                        adapter.setDatas(datas_to_show);
                        stopLoadMore = false;
                    } else {
                        stopLoadMore = true;
                    }
                } else {
                    isLoading = false;
                    stopLoadMore = false;
                }
            } else {
                isLoading = false;
                stopLoadMore = false;
            }
        } else {
            isLoading = false;
            stopLoadMore = false;
        }
    }

    private List<FeedCommentEntity> filterComments(List<FeedCommentEntity> datas_all) {
        List<FeedCommentEntity> local_datas = new ArrayList<>();
        final ArrayList<FeedCommentEntity> selected_local_datas = new ArrayList<>();
        local_datas.addAll(datas_all);
        if (position == 0) {
            for (FeedCommentEntity entity : local_datas) {
                if (entity.is_pos()) {
                    selected_local_datas.add(entity);
                }
            }
        } else if (position == 2) {
            for (FeedCommentEntity entity : local_datas) {
                if (!entity.is_pos()) {
                    selected_local_datas.add(entity);
                }
            }
        } else {
            selected_local_datas.addAll(local_datas);
        }
        return selected_local_datas;
    }

    @Override
    public void showLoading() {
        if (isRefresh) {
            swipe_refresh_layout.setRefreshing(true);
        }
    }

    @Override
    public void hideLoading() {
        swipe_refresh_layout.setRefreshing(false);
    }

    @Override
    public void showError(String errMsg) {
//        Snackbar.make(layout_right_layout, errMsg, Snackbar.LENGTH_SHORT).show();
        MaterialDialog notice_dialog = new MaterialDialog.Builder(getActivity()).title("提示").positiveText("确认").cancelable(false).content(errMsg).build();
        notice_dialog.show();
    }

    private void getPageFeedsComments(boolean refresh) {
        String anchor = "0";
        int current_page = page;
        if (refresh) {
            anchor = "0";
            current_page = 1;
        } else {
            if (datas.size() == 0) {
                anchor = "0";
                current_page = 1;
            } else {
                anchor = datas.get(datas.size() - 1).getCid() + "";
                current_page = current_page + 1;
            }
        }
        if (!refresh) {
            if (stopLoadMore) {
                return;
            } else {
                stopLoadMore = true;
                isLoading = true;
            }
        } else {
            isLoading = true;
            stopLoadMore = true;
        }
        presenter.getComments(is_newest_comment, fid, anchor, current_page + "");
    }

    @Override
    public void onDestroy() {
        if (!rxSubscription.isUnsubscribed()) {
            rxSubscription.unsubscribe();
        }
        super.onDestroy();
    }
}
